# _*_ coding:utf-8 _*_
# @Time  : 2022.10.13
# @Author: zizlee
import json
import datetime
import sys
import time

import requests
import pandas as pd
from urllib3 import disable_warnings
from iFinDPy import THS_iFinDLogin, THS_iFinDLogout, THS_HQ

disable_warnings()

HOST = 'https://210.13.218.130:9000/'


def print_progress_bar(current, total, color, title=''):  # percent是小数
    percent = round(current / total, 4)
    prefix_progress = '▓' * int(80 * percent)
    leave_progress = '▓' * (80 - int(80 * percent))
    print(f'\033[1;{color}m{current}/{total}\033[0m|\033[1;{color}m{prefix_progress}\033[0m{leave_progress} {title}')


def read_indexes(pointers=None):
    with open('THS_品种主力合约行情.json', encoding='utf8', mode='r') as fp:
        indexes = json.load(fp)
    if pointers:
        indexes = list(filter(lambda x: x['source_id'] in pointers, indexes))
    print('读取本地数量:', len(indexes))

    # 读取网络指标数据，过滤并修改起始日期
    r = requests.get(HOST + 'v1/datalib/table/indexGroups/', verify=False)
    customer_indexes = None
    for g in r.json()['data']:
        if g['group'] == 'rj1':
            customer_indexes = g['data']
    # print('读取网络指标数量:', len(customer_indexes))

    local_indexes = {i['source_id']: i['ths_code'] for i in indexes}
    indicates = {i['source_id']: i['ths_indicate'] for i in indexes}

    customer_indexes = list(filter(lambda x: x['source_id'] in local_indexes.keys(), customer_indexes))
    for ci in customer_indexes:
        ci['ths_code'] = local_indexes.get(ci['source_id'])
        ci['ths_indicate'] = indicates.get(ci['source_id'])
        if not ci['ths_code'] or not ci['ths_indicate']:
            raise ValueError(f'{ci["name_zh"]}指标不存在！')
    print('待更新指标数量:', len(customer_indexes))

    return customer_indexes


def get_ths_values(index_item):
    start_date = index_item['enddate'] if index_item['enddate'] else index_item['startdate']
    # 历史行情-期货-收盘价;结算价-iFinD数据接口(codes, indicators, parameters, dataformat)
    ret = THS_HQ(index_item['ths_code'], index_item['ths_indicate'], '', start_date, CLOSE_DATE)
    if ret.errorcode != 0:
        print(
            f'\033[1;34m获取 {index_item["source_id"]} 数据, 起始日期:{start_date}.失败了，code={ret.errorcode} {ret.errmsg} \033[0m')
        return []
    index_data = ret.data[['time', index_item['ths_indicate']]]
    # print(index_data)
    ret_df = index_data.rename(columns={'time': 'datadate', index_item['ths_indicate']: 'datavalue'})
    # 检验date格式
    ret_df['datadate'] = ret_df['datadate'].apply(
        lambda x: datetime.datetime.strptime(x, '%Y-%m-%d').strftime('%Y-%m-%d'))
    ret_df['datavalue'] = pd.to_numeric(ret_df['datavalue'])
    ret_df['datavalue'] = ret_df['datavalue'].astype(float)
    ret_df.fillna(0, inplace=True)
    return ret_df.to_dict(orient='records')


def save_ths_values(sheet_id, datalist):
    if sheet_id not in [2707, 6779, 3513, 2704]:  # 动力煤和强麦的主力收盘价会为0
        datalist = list(filter(lambda x: x['datavalue'] > 0, datalist))
    if len(datalist) <= 1:
        print(datalist, '数据已存在，无需再保存!')
        return 36
    url = HOST + 'v1/datalib/table/update/'
    body_data = {'dataid': sheet_id, 'row_value': datalist}
    r = requests.post(url, json=body_data, verify=False)
    return 35 if r.json()['code'] == 200 else 31


if __name__ == '__main__':
    # while True:
    #     time.sleep(20)
    # if datetime.datetime.now().strftime('%H:%M') == '15:26':
    with open('../ths.config.json', 'r') as ths:
        ths_configs = json.load(ths)

    CLOSE_DATE = datetime.datetime.today().strftime('%Y-%m-%d')
    # CLOSE_DATE = '2023-12-04'
    index_list = read_indexes()
    # index_list = list(filter(lambda x: x['source_id'] == 'R00020046', index_list))
    # login_rep = THS_iFinDLogin(ths_configs['USER'], ths_configs['PSWD'])
    login_rep = THS_iFinDLogin('rdqh085', 'rdrj180912')
    if login_rep != 0:
        raise AssertionError(f'登录THS失败:{login_rep}！')
    total_count = len(index_list)
    for idx, item in enumerate(index_list):
        # if item['id'] not in [2704, 2707]:
        #     continue
        ths_values = get_ths_values(item)
        # print(f'{item["name_zh"]},指标{item["source_id"]},起始日期:{ths_values[0]["datadate"]}', ths_values)
        color_number = save_ths_values(item['id'], ths_values)
        print_progress_bar(current=idx + 1, total=total_count, color=color_number,
                           title=f'{item["name_zh"]},指标{item["source_id"]},起始日期:{ths_values[0]["datadate"]}保存完成.')
        time.sleep(0.2)
    THS_iFinDLogout()

